import QtQuick 1.1
import com.nokia.meego 1.0
import "Logic.js" as Logic

Page {
    id: pageAddWord

    property int lastCategorySelectedIndex: -1

    tools: ToolBarLayout {
        id: tool_only_back
        ToolIcon {
            id: toolIconBack
            //iconId: "toolbar-back"
            iconSource: "images/toolbar/back.png"
            onClicked: {
                pageStack.pop();
                pageWordsList.getAllWords()
            }
        }
        ToolIcon {
            id: toolIconOk
            //iconId: "toolbar-done"
            iconSource: "images/toolbar/ok.png"
            onClicked: {
                var word = wordInput.text
                var trans = translationInput.text

                var str = ""
                var category_id = 0

                if( lastCategorySelectedIndex < 0 ) {
                    str = qsTr("Select a category")
                } else if( (word == "") && (trans == "") ) {
                    str = qsTr("Enter the word and translation")
                } else if( pageWordsList.isEditWord === false) {
                    category_id = listModelCategory.get( lastCategorySelectedIndex ).category_id
                    var ri = Logic.addWord(word, trans,category_id)
                    if(ri) {
                        str = qsTr("Successfully saved !")
                        wordInput.text = ""
                        translationInput.text = ""
                    } else {
                        str = qsTr("Failed to save !")
                    }
                } else {
                    category_id = listModelCategory.get( lastCategorySelectedIndex ).category_id
                    var ru = Logic.updateWord(pageWordsList.selWordId , word, trans,category_id)
                    if(ru) {
                        str = qsTr("Successfully updated !")
                        wordInput.text = ""
                        translationInput.text = ""
                        pageStack.pop();
                        pageWordsList.getAllWords()
                    } else {
                        str = qsTr("Failed to update !")
                    }
                }

                bannerSaveWordOk.openDlg( str )

                //pageStack.pop();
            }
        }
        opacity: userTheme.opacityToolbar
    } //ToolBarLayout


    /************************************************************************/

    function getAllCategories() {
        var db = Logic.getDatabase()

        categorySelectButton.enabled = false
        listModelCategory.clear()

        db.transaction( function(tx) {
                           var res = tx.executeSql( "SELECT id,category FROM categories" )
                           for(var i = 0; i<=res.rows.length-1; i++) {
                               categorySelectButton.enabled = true
                               var _id = res.rows.item(i).id;
                               var nameCategory = res.rows.item(i).category;
                               //var descrCategory = res.rows.item(i).description;
                               listModelCategory.append( { name: nameCategory, category_id: _id } );
                           }
                       }
                    )
        /* установка значение для первого элемента */
        //titlePage.busy = false
    }

    function initForm() {
        //console.log("AddWords::initForm()")
        if( pageWordsList.isEditWord ) {
            wordInput.text = pageWordsList.selWord
            translationInput.text = pageWordsList.selWordTransl

            for( var j =0; j<listModelCategory.count; j++ ) {
                //console.log("listModelCategory.get(j).category_id="+listModelCategory.get(j).category_id+" selWordCategoryId="+pageWordsList.selWordCategoryId)
                if( listModelCategory.get(j).category_id == pageWordsList.selWordCategoryId ) {
                    dlgSelectCategory.selectedIndex = j
                    break
                }
            }
        }
    }

    function removeWord( id ) {
    }

    /************************************************************************/

    ListModel {
        id: listModelCategory
        Component.onCompleted: {
            getAllCategories()
            initForm()
        }
    }

    QNMTitle {
        id: titlePage
        text: pageWordsList.isEditWord ? qsTr("Edit word") : qsTr("Add word")
        image: "images/words.png"
        busy: false
    }

    BackgroundPage { }


    Flickable {
        id: flickArea
        anchors {
            top: titlePage.bottom
            bottom: parent.bottom
            left: parent.left
            right: parent.right
            topMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 5 : 15
            leftMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 40 : 20
            rightMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 40 : 20
            bottomMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 5 : 15
        }

        flickableDirection: Flickable.VerticalFlick

        width: parent.width
        height: parent.height

        contentWidth: contentFlickArea.width
        contentHeight: contentFlickArea.height
        clip: true

        Column {
            id: contentFlickArea
            width: parent.width
            spacing: 10

            Text {
                text: qsTr("Category")
                font.pixelSize: 30
            }
            MyButton {
                id: categorySelectButton
                iconSource: "images/categories_icon.png"
                text: qsTr("List of categories")
                height: 100
                fontSize: 24
                //width: (screen.orientationString == "Portrait") || (screen.orientationString == "PortraitInverted") ? 440 : 810
                width: flickArea.width
                onClicked: {
                    dlgSelectCategory.open()
                }
            }

            Text {
                text: qsTr("Word")
                font.pixelSize: 30
            }

            TextArea {
                id: wordInput
                width: (screen.orientationString == "Portrait") || (screen.orientationString == "PortraitInverted") ? 440 : 810
                height: 200
                wrapMode: TextEdit.WordWrap
                clip: true
            }

            Item { height: 50; width: parent.width }

            Text {
                text: qsTr("Translation")
                font.pixelSize: 30
            }

            TextArea {
                id: translationInput
                width: (screen.orientationString == "Portrait") || (screen.orientationString == "PortraitInverted") ? 440 : 810
                height: 200
                wrapMode: TextEdit.WordWrap
                clip: true
            }

        }
    }

    SelectionDialog {
        id: dlgSelectCategory
        titleText: qsTr("Select a category")
        model: listModelCategory
        onSelectedIndexChanged: {
            var j = selectedIndex
            pageAddWord.lastCategorySelectedIndex = j
            var nc = listModelCategory.get(j).name
            categorySelectButton.text = nc
            //console.log(j+ " " + nc)
        }
    }

    //Component.onCompleted: { ; }

    QueryDialog {
        id: bannerSaveWordOk
        title: Image {
            anchors.horizontalCenter: parent.horizontalCenter
            //source: "image://theme/icon-l-user-guide"
            source: "images/info.png"
        }
        property alias text: bannerSaveWordOk.message
        function openDlg( text ) {
            bannerSaveWordOk.message = text
            bannerSaveWordOk.open()
        }
    }

}
